package com.bxs.command.service;

import com.bxs.pojo.NetWorkInterfaceInfo;
import org.pcap4j.core.PcapAddress;
import org.pcap4j.core.PcapNativeException;
import org.pcap4j.core.PcapNetworkInterface;
import org.pcap4j.core.Pcaps;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
// 有关网卡信息的实现
public class InterfacesService {
    /**
     * 获取网卡信息列表
     */
    public List<NetWorkInterfaceInfo> getAllInterfaces() throws PcapNativeException {
        List<PcapNetworkInterface> allDevs = Pcaps.findAllDevs();
        List<NetWorkInterfaceInfo> collect = allDevs.stream().map((obj) -> {
            NetWorkInterfaceInfo netWorkInterfaceInfo = new NetWorkInterfaceInfo();
            List<String> addrs = new ArrayList<>();
//            System.out.println(123);
            for(PcapAddress address : obj.getAddresses()){
                addrs.add(address.getAddress().getHostName());
            }
            netWorkInterfaceInfo.setAddress(addrs);
            netWorkInterfaceInfo.setDesc(obj.getDescription());
            netWorkInterfaceInfo.setName(obj.getName());
            netWorkInterfaceInfo.setRunning(obj.isRunning());
            netWorkInterfaceInfo.setUp(obj.isUp());
            return netWorkInterfaceInfo;
        }).collect(Collectors.toList());
        return collect;
    }


//    public static void main(String[] args) {
//        InterfacesService interfacesService = new InterfacesService();
//        try {
//            System.out.println(interfacesService.getAllInterfaces());
//        } catch (PcapNativeException e) {
//            e.printStackTrace();
//        }
//    }
}
